<template>
  <el-form
    ref="loginForm"
    :model="loginFormData"
    status-icon
    :rules="rulesV"
    label-width="120px"
    class="demo-loginFormData"
  >
   

    <el-form-item label="手机号" prop="phone" class="captchaname-from-item">
      <el-input v-model="loginFormData.phone" class="captcha_input" />
      <div class="get-label">
      <span @click="sendSms">{{desc}}</span>
      </div>
    </el-form-item>
    <el-form-item label="验证码" prop="number">
      <el-input v-model="loginFormData.number" type="text" autocomplete="off" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="submitForm(loginForm)" class="login"
        >登录</el-button
      >
      <!-- <el-button @click="resetForm(loginForm)">Reset</el-button> -->
    </el-form-item>
  </el-form>
</template>
<script setup>
//引入接口
import * as api from '@/api/index.js'

//引入消息提示
import { ElMessage } from 'element-plus'

//引入store
import { useUser } from "@/store/users";
//引入loading加载框
import { ElLoading } from "element-plus";

//引入路由对象
import { useRouter } from 'vue-router';

import { reactive, ref ,onUnmounted} from "vue";

import { rulesV, useSubmitForm } from "../../composition/login/validate";

console.log(api)

let router = useRouter()

//使用store
let userStore = useUser();

//表单校验成功之后，回调的方法
let validateSuccess = async () => {
  console.log("校验成功");
   //发起登录请求的时候就要加载loading加载框
  let loadingInstance = ElLoading.service({
    lock: true,
    text: "正在输入...",
    background: "rgba(0,0,0,.3)",
  });

  //发送短信登入的请求
  try{
    let res = await api.smsApi(loginFormData.number)
    //关闭loadding加载动画框
    loadingInstance.close()
    console.log(res)
    //储存token，存到sessionStorage中
    sessionStorage.setItem("myx-token", res.data.token);
    //储存用户信息
    userStore.$patch({
      userInfo:res.data.userInfo
    });
    //页面要跳转
    router.push('/')
  }catch(e){
    console.log(e)
    //登录失败也要 关闭loadding加载动画框
    loadingInstance.close()
  }
};
//表单校验失败，回调的方法
let validateFailed = () => {
  console.log("校验失败");
};

//使用submitForm
let submitForm = useSubmitForm(validateSuccess, validateFailed);
const loginForm = ref();

//注入到表单的数据
const loginFormData = reactive({
  phone: "",
  number: "",
});

//短信登入流程
//1.输入手机号，点击发送按钮，获取短信验证码

//短信验证码需要倒计时

//手机验证码同一个手机，一分钟发送一次，一天一个手机号只能发6次

//2.输入短信验证码，进行登入请求

//声明一个响应式变量改变按钮中间的文字
let desc = ref('点击发送')
//引用定时器，便于组件卸载的时候，清楚定时器
let timeDownInterval = null
//处理用户频繁点击的问题
//用开关逻辑,初始值用户未点击
 let isClick = false
let sendSms = async ()=>{
    if(!isClick){
  
    //发起获取短信验证码的请求
    try{
      let res = await api.getSmsCode(loginFormData.phone)
      //给消息提示
      ElMessage({
        message: '短信验证发送成功',
        type: 'success',
      })

      console.log(res)
      //调用倒计时
      timeDownInterval = timeDown(5,desc,'秒后发送',desc.value,()=>{
      //让点击状态isClick恢复到未点击
      isClick = false
    })
    }catch(e){
      console.log(e)
      //将按钮的开关重置
      isClick= false
      ElMessage({
        message: e,
        type: 'error',
      })
      return
    }
    
  }
  //标记isClick已经被点击了
  isClick = true

}


//封装短信倒计时的方法
/**
 * @param {number} timer 倒计时时间
 * @param {object} param 需要变更的响应式变量
 * @param {String} msg 倒计时秒数的文字
 * @param {String} endMsg 倒计时结束之后回显的文字
 * @param {Function} cd 倒计时结束之后回调的函数
 */

 //字符串.padStart('希望补位的位数','用什么字符补')
let timeDown = (timer=5,param,msg,endMsg,cd)=>{
  //实现思路，核心问题就是定时器
  let count = timer
  // 一旦调用倒计时函数，就要显示倒计时数
  param.value = (count+'').padStart(2,0)+msg
  let interval = setInterval(()=>{
    count--
    // console.log(666)
    if(count<=0){
      //清楚定时器
      clearInterval(interval)
      //倒计时结束
      param.value = endMsg
      //回调传入的函数
      cd && cd()
      return
    }
    // console.log(count)
    param.value = (count+'').padStart(2,0)+msg
  },1000)
  //返回定时器的引用
  return interval
}

//组件卸载的钩子
onUnmounted(()=>{
  console.log('组件卸载')
  //如果定时器存在，组件卸载的时候也需要清楚定时器
  if(timeDownInterval) clearInterval(timeDownInterval)
})
</script>
<style lang="less" scoped>
 :deep(.el-input__wrapper) {
  box-shadow: none;
}
.captchaname-from-item{
  .captcha_input {
    width: 120px;
  :deep(.el-input__wrapper) {
    border-radius: 4px 0 0 4px;
  }
}
}
.get-label{
    width: 80px;
}


</style>


